package com.example.service.impl;

import com.example.common.Result;
import com.example.common.PageResult;
import com.example.dto.StoreProductDTO;
import com.example.dto.StoreProductUpdateDTO;
import com.example.entity.StoreProduct;
import com.example.entity.SupplyProduct;
import com.example.entity.StockRecord;
import com.example.entity.User;
import com.example.mapper.StoreProductMapper;
import com.example.mapper.SupplyProductMapper;
import com.example.mapper.StockRecordMapper;
import com.example.service.StoreProductService;
import com.example.service.MemberDiscountService;
import com.example.util.UserContextUtil;
import com.example.vo.StoreProductVO;
import com.example.vo.DiscountInfoVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 店长商品Service实现类
 */
@Slf4j
@Service
public class StoreProductServiceImpl implements StoreProductService {
    
    @Autowired
    private StoreProductMapper storeProductMapper;
    
    @Autowired
    private SupplyProductMapper supplyProductMapper;
    
    @Autowired
    private StockRecordMapper stockRecordMapper;
    
    @Autowired
    private UserContextUtil userContextUtil;
    
    @Autowired
    private MemberDiscountService memberDiscountService;
    
    /**
     * 应用会员折扣信息到商品VO
     */
    private void applyMemberDiscount(StoreProductVO productVO) {
        try {
            // 获取当前用户信息
            User currentUser = userContextUtil.getCurrentUser();
            String memberLevel = "NORMAL"; // 默认普通用户
            
            if (currentUser != null && currentUser.getMemberLevel() != null) {
                memberLevel = currentUser.getMemberLevel();
            }
            
            // 计算会员折扣信息
            Result<DiscountInfoVO> discountResult = memberDiscountService.getMemberDiscountInfo(
                productVO.getSellingPrice(), memberLevel);
            
            if (discountResult.getCode() == 200 && discountResult.getData() != null) {
                DiscountInfoVO discountInfo = discountResult.getData();
                
                // 设置折扣相关字段
                productVO.setUserMemberLevel(memberLevel);
                productVO.setMemberLevelName(discountInfo.getMemberLevelName());
                productVO.setMemberDiscountRate(discountInfo.getDiscountRate());
                productVO.setMemberDiscountPrice(discountInfo.getDiscountPrice());
                productVO.setSavedAmount(discountInfo.getSavedAmount());
                productVO.setDiscountDescription(discountInfo.getDiscountDescription());
                productVO.setHasMemberDiscount(discountInfo.getHasDiscount());
                
                log.debug("应用会员折扣 - 商品: {}, 会员等级: {}, 原价: {}, 折扣价: {}, 节省: {}", 
                    productVO.getProductName(), memberLevel, productVO.getSellingPrice(), 
                    discountInfo.getDiscountPrice(), discountInfo.getSavedAmount());
            }
        } catch (Exception e) {
            log.warn("应用会员折扣失败，商品ID: {}", productVO.getId(), e);
            // 出错时设置默认值，不影响基本功能
            productVO.setUserMemberLevel("NORMAL");
            productVO.setMemberLevelName("普通用户");
            productVO.setHasMemberDiscount(false);
        }
    }
    
    @Override
    @Transactional
    public Result<Void> addStoreProduct(StoreProductDTO storeProductDTO) {
        try {
            // 获取当前店长ID
            Long storeManagerId = userContextUtil.getCurrentUserId();
            if (storeManagerId == null) {
                return Result.error("用户未登录");
            }
            
            // 验证供货商品是否存在
            SupplyProduct supplyProduct = supplyProductMapper.selectById(storeProductDTO.getSupplyProductId());
            if (supplyProduct == null) {
                return Result.error("供货商品不存在");
            }
            
            // 查找店长是否已经进货该商品（通过入库明细管理创建的店长商品记录）
            StoreProduct existingStoreProduct = storeProductMapper.selectByStoreManagerAndSupplyProduct(storeManagerId, storeProductDTO.getSupplyProductId());
            if (existingStoreProduct == null) {
                return Result.error("您还没有进货该商品，请先通过入库明细管理进行进货");
            }
            
            // 更新商品信息（不管当前状态如何，都允许重新设置）
            if (storeProductDTO.getProductName() != null) {
                existingStoreProduct.setProductName(storeProductDTO.getProductName());
            }
            if (storeProductDTO.getProductCode() != null) {
                existingStoreProduct.setProductCode(storeProductDTO.getProductCode());
            }
            if (storeProductDTO.getModel() != null) {
                existingStoreProduct.setModel(storeProductDTO.getModel());
            }
            if (storeProductDTO.getImage() != null) {
                existingStoreProduct.setImage(storeProductDTO.getImage());
            }
            existingStoreProduct.setSellingPrice(storeProductDTO.getSellingPrice());
            existingStoreProduct.setStatus(storeProductDTO.getStatus() != null ? storeProductDTO.getStatus() : 1);
            existingStoreProduct.setDeleted(0); // 确保未删除
            existingStoreProduct.setUpdateTime(LocalDateTime.now());
            
            int result = storeProductMapper.updateById(existingStoreProduct);
            if (result > 0) {
                String statusText = existingStoreProduct.getStatus() == 1 ? "上架" : "下架";
                log.info("店长商品{}成功，商品名称: {}, 店长ID: {}", statusText, supplyProduct.getProductName(), storeManagerId);
                return Result.success();
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            log.error("上架商品失败", e);
            return Result.error("上架商品失败");
        }
    }
    
    @Override
    @Transactional
    public Result<Void> deleteStoreProduct(Long id) {
        try {
            Long storeManagerId = userContextUtil.getCurrentUserId();
            if (storeManagerId == null) {
                return Result.error("用户未登录");
            }
            
            StoreProduct storeProduct = storeProductMapper.selectById(id);
            if (storeProduct == null) {
                return Result.error("商品不存在");
            }
            
            // 验证是否是当前店长的商品
            if (!storeProduct.getStoreManagerId().equals(storeManagerId)) {
                return Result.error("无权限操作该商品");
            }
            
            int result = storeProductMapper.deleteById(id);
            if (result > 0) {
                log.info("删除店长商品成功，商品ID: {}", id);
                return Result.success();
            } else {
                return Result.error("删除商品失败");
            }
        } catch (Exception e) {
            log.error("删除店长商品失败，商品ID: {}", id, e);
            return Result.error("删除商品失败");
        }
    }
    
    @Override
    @Transactional
    public Result<Void> updateStoreProduct(Long id, StoreProductDTO storeProductDTO) {
        try {
            Long storeManagerId = userContextUtil.getCurrentUserId();
            if (storeManagerId == null) {
                return Result.error("用户未登录");
            }
            
            StoreProduct existingProduct = storeProductMapper.selectById(id);
            if (existingProduct == null) {
                return Result.error("商品不存在");
            }
            
            // 验证是否是当前店长的商品
            if (!existingProduct.getStoreManagerId().equals(storeManagerId)) {
                return Result.error("无权限操作该商品");
            }
            
            // 更新商品信息
            if (storeProductDTO.getProductName() != null) {
                existingProduct.setProductName(storeProductDTO.getProductName());
            }
            if (storeProductDTO.getProductCode() != null) {
                existingProduct.setProductCode(storeProductDTO.getProductCode());
            }
            if (storeProductDTO.getModel() != null) {
                existingProduct.setModel(storeProductDTO.getModel());
            }
            if (storeProductDTO.getImage() != null) {
                existingProduct.setImage(storeProductDTO.getImage());
            }
            existingProduct.setSellingPrice(storeProductDTO.getSellingPrice());
            existingProduct.setMinStock(storeProductDTO.getMinStock() != null ? storeProductDTO.getMinStock() : existingProduct.getMinStock());
            existingProduct.setStatus(storeProductDTO.getStatus() != null ? storeProductDTO.getStatus() : existingProduct.getStatus());
            existingProduct.setUpdateTime(LocalDateTime.now());
            
            int result = storeProductMapper.updateById(existingProduct);
            if (result > 0) {
                log.info("更新店长商品成功，商品ID: {}", id);
                return Result.success();
            } else {
                return Result.error("更新商品失败");
            }
        } catch (Exception e) {
            log.error("更新店长商品失败，商品ID: {}", id, e);
            return Result.error("更新商品失败");
        }
    }
    
    @Override
    public Result<StoreProductVO> getStoreProductById(Long id) {
        try {
            Long storeManagerId = userContextUtil.getCurrentUserId();
            if (storeManagerId == null) {
                return Result.error("用户未登录");
            }
            
            StoreProduct storeProduct = storeProductMapper.selectById(id);
            if (storeProduct == null) {
                return Result.error("商品不存在");
            }
            
            // 验证是否是当前店长的商品
            if (!storeProduct.getStoreManagerId().equals(storeManagerId)) {
                return Result.error("无权限查看该商品");
            }
            
            // 查询详细信息
            List<StoreProductVO> products = storeProductMapper.selectPageWithDetails(storeManagerId, null, null);
            StoreProductVO productVO = products.stream()
                    .filter(p -> p.getId().equals(id))
                    .findFirst()
                    .orElse(null);
            
            if (productVO != null) {
                return Result.success(productVO);
            } else {
                return Result.error("商品信息查询失败");
            }
        } catch (Exception e) {
            log.error("查询店长商品失败，商品ID: {}", id, e);
            return Result.error("查询商品失败");
        }
    }
    
    @Override
    public Result<PageResult<StoreProductVO>> getStoreProductPage(int page, int size, String keyword, Integer status) {
        try {
            Long storeManagerId = userContextUtil.getCurrentUserId();
            if (storeManagerId == null) {
                return Result.error("用户未登录");
            }
            
            PageHelper.startPage(page, size);
            List<StoreProductVO> list = storeProductMapper.selectPageWithDetails(storeManagerId, keyword, status);
            PageInfo<StoreProductVO> pageInfo = new PageInfo<>(list);
            
            // 设置状态名称
            for (StoreProductVO product : list) {
                product.setStatusName(product.getStatus() == 1 ? "上架" : "下架");
            }
            
            PageResult<StoreProductVO> pageResult = new PageResult<>();
            pageResult.setRecords(list);
            pageResult.setTotal(pageInfo.getTotal());
            pageResult.setPages(pageInfo.getPages());
            pageResult.setCurrent(page);
            pageResult.setSize(size);
            
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("分页查询店长商品失败", e);
            return Result.error("查询商品列表失败");
        }
    }
    
    @Override
    public Result<PageResult<StoreProductVO>> getOnlineProducts(Long storeManagerId, int page, int size, String keyword) {
        try {
            PageHelper.startPage(page, size);
            List<StoreProductVO> list = storeProductMapper.selectOnlineProducts(storeManagerId, keyword);
            PageInfo<StoreProductVO> pageInfo = new PageInfo<>(list);
            
            // 为每个商品应用会员折扣
            for (StoreProductVO product : list) {
                product.setStatusName(product.getStatus() == 1 ? "上架" : "下架");
                applyMemberDiscount(product);
            }
            
            PageResult<StoreProductVO> pageResult = new PageResult<>();
            pageResult.setRecords(list);
            pageResult.setTotal(pageInfo.getTotal());
            pageResult.setPages(pageInfo.getPages());
            pageResult.setCurrent(page);
            pageResult.setSize(size);
            
            log.info("查询上架商品成功，店长ID: {}, 返回{}条记录", storeManagerId, list.size());
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("查询上架商品失败", e);
            return Result.error("查询商品列表失败");
        }
    }
    
    @Override
    @Transactional
    public Result<Void> updateProductStatus(Long id, Integer status) {
        try {
            Long storeManagerId = userContextUtil.getCurrentUserId();
            if (storeManagerId == null) {
                return Result.error("用户未登录");
            }
            
            StoreProduct storeProduct = storeProductMapper.selectById(id);
            if (storeProduct == null) {
                return Result.error("商品不存在");
            }
            
            // 验证是否是当前店长的商品
            if (!storeProduct.getStoreManagerId().equals(storeManagerId)) {
                return Result.error("无权限操作该商品");
            }
            
            storeProduct.setStatus(status);
            storeProduct.setUpdateTime(LocalDateTime.now());
            
            int result = storeProductMapper.updateById(storeProduct);
            if (result > 0) {
                log.info("更新商品状态成功，商品ID: {}, 状态: {}", id, status);
                return Result.success();
            } else {
                return Result.error("更新商品状态失败");
            }
        } catch (Exception e) {
            log.error("更新商品状态失败，商品ID: {}", id, e);
            return Result.error("更新商品状态失败");
        }
    }
    
    @Override
    @Transactional
    public Result<Void> stockIn(Long id, Integer quantity) {
        try {
            Long storeManagerId = userContextUtil.getCurrentUserId();
            if (storeManagerId == null) {
                return Result.error("用户未登录");
            }
            
            StoreProduct storeProduct = storeProductMapper.selectById(id);
            if (storeProduct == null) {
                return Result.error("商品不存在");
            }
            
            // 验证是否是当前店长的商品
            if (!storeProduct.getStoreManagerId().equals(storeManagerId)) {
                return Result.error("无权限操作该商品");
            }
            
            // 记录更新前的库存
            int beforeStock = storeProduct.getCurrentStock();
            int afterStock = beforeStock + quantity;

            // 更新库存
            int result = storeProductMapper.updateStock(id, afterStock);

            if (result > 0) {
                // 创建入库记录
                createStockInRecord(storeProduct, quantity, beforeStock, afterStock, "商品入库");
                
                log.info("商品入库成功，商品ID: {}, 入库数量: {}", id, quantity);
                return Result.success();
            } else {
                return Result.error("商品入库失败");
            }
        } catch (Exception e) {
            log.error("商品入库失败，商品ID: {}", id, e);
            return Result.error("商品入库失败");
        }
    }
    
    /**
     * 创建入库记录
     */
    private void createStockInRecord(StoreProduct storeProduct, Integer quantity, Integer beforeStock, Integer afterStock, String remark) {
        try {
            // 获取操作员姓名
            String operatorName = userContextUtil.getCurrentUserNickname();
            if (operatorName == null || operatorName.trim().isEmpty()) {
                operatorName = userContextUtil.getCurrentUsername();
                if (operatorName == null || operatorName.trim().isEmpty()) {
                    operatorName = "系统用户";
                }
            }

            StockRecord stockRecord = new StockRecord();
            stockRecord.setRecordNo(generateRecordNo());
            // 使用供货商品ID，保持与入库明细管理的记录一致
            stockRecord.setProductId(storeProduct.getSupplyProductId());
            stockRecord.setProductName(storeProduct.getProductName());
            stockRecord.setProductCode(storeProduct.getProductCode());
            stockRecord.setRecordType("IN");
            stockRecord.setQuantity(quantity);
            stockRecord.setBeforeStock(beforeStock);
            stockRecord.setAfterStock(afterStock);
            stockRecord.setOperatorId(storeProduct.getStoreManagerId());
            stockRecord.setOperatorName(operatorName + "(店长入库)"); // 标识为店长入库，使其显示在店长端
            stockRecord.setRemark(remark);
            stockRecord.setCreateTime(LocalDateTime.now());
            stockRecord.setUpdateTime(LocalDateTime.now());
            stockRecord.setDeleted(0);

            stockRecordMapper.insert(stockRecord);
        } catch (Exception e) {
            log.error("创建入库记录失败", e);
        }
    }
    
    /**
     * 生成记录编号
     */
    private String generateRecordNo() {
        LocalDateTime now = LocalDateTime.now();
        String dateStr = String.format("%04d%02d%02d%02d%02d%02d",
                now.getYear(), now.getMonthValue(), now.getDayOfMonth(),
                now.getHour(), now.getMinute(), now.getSecond());
        return "SR" + dateStr + String.format("%03d", (int)(Math.random() * 1000));
    }

    @Override
    public Result<Integer> getStockBySupplyProductId(Long supplyProductId) {
        try {
            Long storeManagerId = userContextUtil.getCurrentUserId();
            if (storeManagerId == null) {
                return Result.error("用户未登录");
            }

            // 查询店长是否已上架该供货商品
            StoreProduct storeProduct = storeProductMapper.selectByStoreManagerAndSupplyProduct(storeManagerId, supplyProductId);

            if (storeProduct != null) {
                return Result.success(storeProduct.getCurrentStock());
            } else {
                // 如果没有上架，返回0库存
                return Result.success(0);
            }
        } catch (Exception e) {
            log.error("查询店长商品库存失败，供货商品ID: {}", supplyProductId, e);
            return Result.error("查询库存失败");
        }
    }

    @Override
    public Result<Void> updateStoreProduct(Long id, StoreProductUpdateDTO updateDTO) {
        try {
            Long storeManagerId = userContextUtil.getCurrentUserId();
            if (storeManagerId == null) {
                return Result.error("用户未登录");
            }

            StoreProduct storeProduct = storeProductMapper.selectById(id);
            if (storeProduct == null) {
                return Result.error("商品不存在");
            }

            // 验证是否是当前店长的商品
            if (!storeProduct.getStoreManagerId().equals(storeManagerId)) {
                return Result.error("无权限操作该商品");
            }

            // 更新字段（只允许修改商品名称、销售价格、图片和状态）
            if (updateDTO.getProductName() != null) {
                storeProduct.setProductName(updateDTO.getProductName());
            }
            if (updateDTO.getSellingPrice() != null) {
                storeProduct.setSellingPrice(updateDTO.getSellingPrice());
            }
            if (updateDTO.getImage() != null) {
                storeProduct.setImage(updateDTO.getImage());
            }
            if (updateDTO.getStatus() != null) {
                storeProduct.setStatus(updateDTO.getStatus());
            }
            storeProduct.setUpdateTime(LocalDateTime.now());

            int result = storeProductMapper.updateById(storeProduct);
            if (result > 0) {
                log.info("更新店长商品字段成功，商品ID: {}", id);
                return Result.success();
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新店长商品字段失败，商品ID: {}", id, e);
            return Result.error("更新失败");
        }
    }
    
    @Override
    public Result<PageResult<StoreProductVO>> getAvailableProductsForShelf(int page, int size, String keyword) {
        try {
            Long storeManagerId = userContextUtil.getCurrentUserId();
            if (storeManagerId == null) {
                return Result.error("用户未登录");
            }
            
            PageHelper.startPage(page, size);
            List<StoreProductVO> list = storeProductMapper.selectAvailableProductsForShelf(storeManagerId, keyword);
            PageInfo<StoreProductVO> pageInfo = new PageInfo<>(list);
            
            PageResult<StoreProductVO> pageResult = new PageResult<>();
            pageResult.setRecords(list);
            pageResult.setTotal(pageInfo.getTotal());
            pageResult.setPages(pageInfo.getPages());
            pageResult.setCurrent(page);
            pageResult.setSize(size);
            
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("查询可上架商品失败", e);
            return Result.error("查询可上架商品失败");
        }
    }

    @Override
    public Result<StoreProductVO> getPublicProductDetail(Long id) {
        try {
            StoreProduct storeProduct = storeProductMapper.selectById(id);
            if (storeProduct == null) {
                return Result.error("商品不存在");
            }
            
            // 只允许查看已上架的商品
            if (storeProduct.getStatus() != 1) {
                return Result.error("商品已下架");
            }
            
            // 查询详细信息（不需要权限检查，任何用户都可以查看上架商品）
            List<StoreProductVO> products = storeProductMapper.selectPageWithDetails(storeProduct.getStoreManagerId(), null, 1);
            StoreProductVO productVO = products.stream()
                    .filter(p -> p.getId().equals(id))
                    .findFirst()
                    .orElse(null);
            
            if (productVO != null) {
                // 设置状态名称
                productVO.setStatusName(productVO.getStatus() == 1 ? "上架" : "下架");
                
                // 应用会员折扣
                applyMemberDiscount(productVO);
                
                log.info("查询公开商品详情成功，商品ID: {}, 商品名称: {}, 会员等级: {}, 折扣价: {}", 
                    id, productVO.getProductName(), productVO.getUserMemberLevel(), productVO.getMemberDiscountPrice());
                return Result.success(productVO);
            } else {
                return Result.error("商品信息查询失败");
            }
        } catch (Exception e) {
            log.error("查询公开商品详情失败，商品ID: {}", id, e);
            return Result.error("查询商品详情失败");
        }
    }
}